﻿//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.Rights;
using EffiProz.Core.Errors;

namespace EffiProz.Core
{

    /**
     * Provides Name Management for SQL objects. <p>
     *
     * This class now includes the HsqlNameManager.QName class introduced _in 1.7.1 and improves
     * auto-naming with multiple databases _in the engine.<p>
     *
     * Methods check user defined names and issue system generated names
     * for SQL objects.<p>
     *
     * This class does not deal with the type of the SQL object for which it
     * is used.<p>
     *
     * Some names beginning with SYS_ are reserved for system generated names.
     * These are defined _in isReserveName(string name) and created by the
     * makeAutoName(string type) factory method<p>
     *
     * sysNumber is used to generate system-generated names. It is
     * set to the largest integer encountered _in names that use the
     * SYS_xxxxxxx_INTEGER format. As the DDL is processed before any ALTER
     * command, any new system generated name will have a larger integer suffix
     * than all the existing names.
     *
     * @author fredt@users
     * @version 1.8.0
     * @since 1.7.2
     */
    public class QNameManager
    {

        public const String DEFAULT_CATALOG_NAME = "PUBLIC";
        private static QNameManager staticManager = new QNameManager(null);

        private static QName[] autoColumnNames = new QName[32];
        private static String[] autoNoNameColumnNames = new String[32];

        static QNameManager()
        {
            staticManager.serialNumber = int.MinValue;
            for (int i = 0; i < autoColumnNames.Length; i++)
            {
                autoColumnNames[i] = new QName(staticManager, "C" + (i + 1), 0,
                                                  false);
                autoNoNameColumnNames[i] = (i).ToString();
            }
        }

        private int serialNumber = 1;    // 0 is reserved _in lookups
        private int sysNumber = 0;
        private QName catalogName;

        public QNameManager(Database database)
        {
            catalogName = new QName(this, DEFAULT_CATALOG_NAME,
                                       SchemaObjectTypes.CATALOG, false);
        }

        public QName getCatalogName()
        {
            return catalogName;
        }

        public static QName newSystemObjectName(string name, int type)
        {
            return new QName(staticManager, name, type, false);
        }

        public static QName newInfoSchemaColumnName(String name,
        QName table)
        {

            QName hsqlName = new QName(staticManager, name, false,
                                             SchemaObjectTypes.COLUMN);

            hsqlName.schema = SqlInvariants.INFORMATION_SCHEMA_QNAME;
            hsqlName.parent = table;

            return hsqlName;
        }

        public static QName newInfoSchemaTableName(String name)
        {

            QName hsqlName = new QName(staticManager, name,
                                             SchemaObjectTypes.TABLE, false);

            hsqlName.schema = SqlInvariants.INFORMATION_SCHEMA_QNAME;

            return hsqlName;
        }

        public static QName newInfoSchemaObjectName(String name,
                bool isQuoted, int type)
        {

            QName hsqlName = new QName(staticManager, name, type, isQuoted);

            hsqlName.schema = SqlInvariants.INFORMATION_SCHEMA_QNAME;

            return hsqlName;
        }

        public QName newHsqlName(string name, bool isquoted, int type)
        {
            return new QName(this, name, isquoted, type);
        }

        public QName newHsqlName(QName schema, string name, bool isquoted, int type)
        {
            QName qName = new QName(this, name, isquoted, type);
            qName.schema = schema;
            return qName;
        }

        public QName newHsqlName(QName schema, String name, int type)
        {

            QName hsqlName = new QName(this, name, type, false);

            hsqlName.schema = schema;

            return hsqlName;
        }

        public QName newHsqlName(QName schema, string name, bool isquoted, int type, QName parent)
        {
            QName qName = new QName(this, name, isquoted, type);
            qName.schema = schema;
            qName.parent = parent;
            return qName;
        }

        public QName newColumnSchemaHsqlName(QName table, SimpleName name)
        {
            QName newName = newColumnHsqlName(table, name.name, name.isNameQuoted);
            newName.originalName = name.originalName;
            return newName;
        }

        public QName newColumnHsqlName(QName table, String name,
                                          bool isquoted)
        {

            QName hsqlName = new QName(this, name, isquoted,
                                             SchemaObjectTypes.COLUMN);

            hsqlName.schema = table.schema;
            hsqlName.parent = table;

            return hsqlName;
        }

        /**
         * Same name string but different objects and serial number
         */
        public QName getSubqueryTableName()
        {

            QName hsqlName = new QName(this, SqlInvariants.SYSTEM_SUBQUERY,
                                             false, SchemaObjectTypes.TABLE);

            hsqlName.schema = SqlInvariants.SYSTEM_SCHEMA_QNAME;

            return hsqlName;
        }


        /**
         * Auto names are used for autogenerated indexes or anonymous constraints.
         */
        public QName newAutoName(String prefix, QName schema,
                                    QName parent, int type)
        {

            QName name = newAutoName(prefix, (String)null, schema, parent,
                                        type);

            return name;
        }

        public QName newSpecificRoutineName(QName name)
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(name.name).Append('_').Append(++sysNumber);

            QName hsqlName = new QName(this, sb.ToString(),
                                             SchemaObjectTypes.SPECIFIC_ROUTINE,
                                             name.isNameQuoted);

            hsqlName.parent = name;
            hsqlName.schema = name.schema;

            return hsqlName;
        }

        /**
        * Column index i is 0 based, returns 1 based numbered column.
         */
        static public QName getAutoColumnName(int i)
        {

            if (i < autoColumnNames.Length)
            {
                return autoColumnNames[i];
            }

            return new QName(staticManager, "C_" + (i + 1), 0, false);
        }

        /**
         * Column index i is 0 based, returns 1 based numbered column.
         */
        static public String getAutoColumnNameString(int i)
        {
            if (i < autoColumnNames.Length)
            {
                return autoColumnNames[i].name;
            }

            return "C" + (i + 1);
        }

        static public String getAutoNoNameColumnString(int i)
        {

            if (i < autoColumnNames.Length)
            {
                return autoNoNameColumnNames[i];
            }

            return i.ToString();
        }

        static public String getAutoSavepointNameString(long i, int j)
        {

            StringBuilder sb = new StringBuilder("S");

            sb.Append(i).Append('_').Append(j);

            return sb.ToString();
        }


        /**
         * Auto names are used for autogenerated indexes or anonymous constraints.
         */
        public QName newAutoName(String prefix, String namepart, QName schema,
                         QName parent, int type)
        {

            StringBuilder sbname = new StringBuilder();

            if (prefix != null)
            {
                if (prefix.Length != 0)
                {
                    sbname.Append("SYS_");
                    sbname.Append(prefix);
                    sbname.Append('_');

                    if (namepart != null)
                    {
                        sbname.Append(namepart);
                        sbname.Append('_');
                    }

                    sbname.Append(++sysNumber);
                }
            }
            else
            {
                sbname.Append(namepart);
            }

            QName qName = new QName(this, sbname.ToString(), type, false);
            qName.schema = schema;
            qName.parent = parent;
            return qName;
        }

        public void resetNumbering()
        {
            sysNumber = 0;
            serialNumber = 0;
        }

        public static SimpleName getSimpleName(String name, bool isNameQuoted)
        {
            return new SimpleName(name, isNameQuoted);
        }

        public class SimpleName
        {

            public String name;
            protected string _originalName = String.Empty;
            public bool isNameQuoted;


            public virtual string originalName
            {
                get
                {
                    if (String.IsNullOrEmpty(_originalName))
                        return name;
                    else
                        return _originalName;
                }

                set
                {
                    _originalName = value;
                  
                }
            }

            protected SimpleName() { }

            public SimpleName(String name, bool isNameQuoted)
            {
                this.name = name;
                this.isNameQuoted = isNameQuoted;
            }

            public override int GetHashCode()
            {
                return name.GetHashCode();
            }

            public override bool Equals(Object other)
            {

                if (other is SimpleName)
                {
                    return ((SimpleName)other).isNameQuoted == isNameQuoted
                           && ((SimpleName)other).name.Equals(name);
                }

                return false;
            }

            public String getStatementName()
            {

                return isNameQuoted
                       ? StringConverter.toQuotedString(originalName, '"', true)
                       : originalName;
            }
        }

        public sealed class QName : SimpleName
        {

            public static QNameManager.QName[] emptyArray = new QNameManager.QName[] { };

            public QNameManager manager;
            private string _statementName;            
            private string _originalStatementName = String.Empty;
            public QName parent;
            public QName schema;
            public Grantee owner;
            public int type;
            private int _hashCode;           


            public string statementName
            {
                get
                {
                    if (String.IsNullOrEmpty(_originalStatementName))
                        return _statementName;
                    else
                        return _originalStatementName;
                }
            }

            public override string originalName
            {
                get
                {
                    if (String.IsNullOrEmpty(_originalName))
                        return name;
                    else
                        return _originalName;
                }

                set
                {
                    _originalName = _originalStatementName = value;
                    if (isNameQuoted)
                    {
                        _originalStatementName = StringConverter.toQuotedString(_originalName, '"',
                                true);
                    }
                }
            }

            private QName(QNameManager man, int type)
            {
                manager = man;
                this.type = type;
                _hashCode = manager.serialNumber++;
            }

            public QName(QNameManager man, string name, bool isquoted, int type)
                : this(man, type)
            {

                rename(name, isquoted);
            }

            /** for auto names and system-defined names */
            public QName(QNameManager man, string name, int type,
                             bool isquoted)
                : this(man, type)
            {

                this.name = _statementName = name;
                this.isNameQuoted = isquoted;

                if (isNameQuoted)
                {
                    _statementName = StringConverter.toQuotedString(name, '"',
                            true);
                }
            }

            public String getSchemaQualifiedStatementName()
            {

                if (type == SchemaObjectTypes.COLUMN)
                {
                    if (parent == null
                            || SqlInvariants.SYSTEM_SUBQUERY.Equals(parent.name))
                    {
                        return statementName;
                    }
                    StringBuilder sb = new StringBuilder();

                    if (schema != null)
                    {
                        sb.Append(schema.getStatementName());
                        sb.Append('.');
                    }

                    sb.Append(parent.getStatementName());
                    sb.Append('.');
                    sb.Append(statementName);

                    return sb.ToString();
                }

                if (schema == null)
                {
                    return statementName;
                }

                StringBuilder sb1 = new StringBuilder();

                if (schema != null)
                {
                    sb1.Append(schema.getStatementName());
                    sb1.Append('.');
                }

                sb1.Append(statementName);

                return sb1.ToString();
            }


            public void rename(QName name)
            {
                rename(name.name, name.isNameQuoted);
                originalName = name.originalName;
            }

            public void rename(string name, bool isquoted)
            {
                if (name.Length > 128)
                {
                    throw Error.error(ErrorCode.X_42501, name);
                }

                this.name = name;
                _statementName = name;
                this.isNameQuoted = isquoted;

                if (isNameQuoted)
                {
                    _statementName = StringConverter.toQuotedString(name, '"',
                            true);
                }

                if (name.StartsWith("SYS_"))
                {
                    int length = sysPrefixLength(name);

                    if (length > 0)
                    {
                        try
                        {
                            int temp = int.Parse(name.Substring(length));

                            if (temp > manager.sysNumber)
                            {
                                manager.sysNumber = temp;
                            }
                        }
                        catch (FormatException) { }
                    }
                }
            }

            public void rename(string prefix, string name, bool isquoted)
            {

                StringBuilder sbname = new StringBuilder(prefix);

                sbname.Append('_');
                sbname.Append(name);
                rename(sbname.ToString(), isquoted);
            }

            public void setSchemaIfNull(QName schema)
            {

                if (this.schema == null)
                {
                    this.schema = schema;
                }
            }

            public override bool Equals(Object other)
            {

                if (other is QName)
                {
                    return _hashCode == ((QName)other).GetHashCode();
                }

                return false;
            }

            /**
             * hash code for this object is its unique serial number.
             */
            public override int GetHashCode()
            {
                return _hashCode;
            }

            /**
             * "SYS_IDX_" is used for auto-indexes on referring FK columns or
             * unique constraints.
             * "SYS_PK_" is for the primary key constraints
             * "SYS_CT_" is for unique and check constraints
             * "SYS_REF_" is for FK constraints _in referenced tables
             * "SYS_FK_" is for FK constraints _in referencing tables
             *
             */
            static String[] sysPrefixes = new String[] {
             "SYS_IDX_", "SYS_PK_", "SYS_REF_", "SYS_CT_", "SYS_FK_",
        };

            public static int sysPrefixLength(string name)
            {

                for (int i = 0; i < sysPrefixes.Length; i++)
                {
                    if (name.StartsWith(sysPrefixes[i]))
                    {
                        return sysPrefixes[i].Length;
                    }
                }

                return 0;
            }

            public static bool isReservedName(string name)
            {
                return sysPrefixLength(name) > 0;
            }

            public bool isReservedName()
            {
                return isReservedName(name);
            }

            public override string ToString()
            {

                return GetType().Name + base.GetHashCode()
                       + "[this.GetHashCode()=" + this.GetHashCode() + ", name=" + name
                       + ", name.GetHashCode()=" + name.GetHashCode()
                       + ", isNameQuoted=" + isNameQuoted + "]";
            }

            public int CompareTo(Object o)
            {
                return _hashCode - o.GetHashCode();
            }

            /**
             * Returns true if the identifier consists of all uppercase letters
             * digits and underscore, beginning with a letter and is not _in the
             * keyword list.
             */
            public static bool isRegularIdentifier(string name)
            {

                for (int i = 0, length = name.Length; i < length; i++)
                {
                    int c = name[(i)];

                    if (c >= 'A' && c <= 'Z')
                    {
                        continue;
                    }
                    else if (c == '_' && i > 0)
                    {
                        continue;
                    }
                    else if (c >= '0' && c <= '9')
                    {
                        continue;
                    }

                    return false;
                }

                return !Tokens.isKeyword(name);
            }
        }
    }
}
